package backtrack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 131. 分割回文串
 * User: Li_yizYa
 * Date: 2025/6/17
 * Time: 11:21
 */
public class Solution6 {
    public List<List<String>> partition(String s) {
        List<List<String>> ret = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return ret;
        }
        List<String> tmp = new ArrayList<>();
        StringBuilder str = new StringBuilder();
        backTracking(ret, tmp, s, str, 0);
        return ret;


    }
    private void backTracking(List<List<String>> ret, List<String> tmp, String s, StringBuilder str, int index) {
        if (index == s.length()) {
            ret.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = index; i < s.length(); i++) {
            str.append(s.charAt(i));
            if (check(str)) {
                tmp.add(str.toString());
                backTracking(ret, tmp, s, new StringBuilder(), i + 1);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
    private boolean check(StringBuilder str) {
        int left = 0;
        int right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
